﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using QLNH.MyLayouts;
using QLNH.QLNH_BUS_WS;
using QLNH.MyUserControls;
using System.Threading;

namespace QLNH.MyForms
{
    public partial class AdminAccountManagement : FormUC
    {
        public AdminAccountManagement(LayoutUC mainLayout)
        {
            InitializeComponent();
            this._mainLayout = mainLayout;
            this._formKey = FormKey.ADMIN_ACCOUNT_MANAGEMENT;
        }

        #region Functions

        public override void Resize(Size size)
        {
            if (this.Size.Width < size.Width)
            {
                this.Location = new Point(size.Width / 2 - this.Size.Width / 2, size.Height / 2 - this.Size.Height / 2 + 40);
            }
            else
            {
                this.Location = new Point(0, 0);
            }
        }

        //hien thi cac tai khoan
        private void ShowAccount()
        {
            this.lv_accounts.Items.Clear();
            Thread t = new Thread(new ThreadStart(ShowAccountThread));
            t.SetApartmentState(ApartmentState.STA);
            t.Start();
        }

        private RoleDTO[] _roleList = null;
        private List<AccountDetailDTO> _accountList = null;

        private void ShowAccountThread()
        {
            QLNH_BUS_WebServiceSoapClient ws = new QLNH_BUS_WebServiceSoapClient();
            if (_accountList == null)
            {
                _accountList = new List<AccountDetailDTO>();
                AccountDetailDTO[] temp = ws.GetAllAccountDetail("", "");
                _accountList = temp.ToList<AccountDetailDTO>();
            }

            if (_roleList == null)
            {
                _roleList = ws.GetAllRole();
                this.searchToolbar.BeginInvoke((MethodInvoker)(() => this.searchToolbar.SetGroupComboboxData(_roleList, "Name", "ID")));
            }

            List<AccountDetailDTO> accountDetails = _accountList.FindAll(e => e.UserName.IndexOf(_userNameToFind) >= 0 && e.Role.IndexOf(_roleToFind) >= 0);

            for (int i = 0; i < accountDetails.Count(); i++)
            {
                ListViewItem li = new ListViewItem();
                li.Text = accountDetails[i].ID;
                li.Name = accountDetails[i].Role;
                li.SubItems.Add(accountDetails[i].UserName);
                li.SubItems.Add(accountDetails[i].FullName);
                li.SubItems.Add(accountDetails[i].Role);

                if (this.lv_accounts.Items.Count % 2 != 0)
                {
                    li.BackColor = Color.LightGray;
                }

                if (accountDetails[i].Role.Equals("admin"))
                {
                    li.BackColor = Color.Cyan;
                }

                this.lv_accounts.BeginInvoke((MethodInvoker)(() => this.lv_accounts.Items.Add(li)));
                Thread.Sleep(50);
            }
        }

        #endregion

        #region Control Events

        private void AdminAccountManagement_Load(object sender, EventArgs e)
        {
            ShowAccount();
            this.tooltip.Show("Nhắp chuột vào đây để sắp xếp lại", this.lv_accounts, new Point(0, 0), 1000);
        }

        private void editAction(object sender, EventArgs e)
        {
            int id = this.lv_accounts.SelectedItems[0].Index;
            string accID = this.lv_accounts.Items[id].SubItems[0].Text;
            string username = this.lv_accounts.Items[id].SubItems[1].Text;
            string fullname = this.lv_accounts.Items[id].SubItems[2].Text;
            string accType = this.lv_accounts.Items[id].SubItems[3].Text;

            this._mainLayout.SwitchForm(FormKey.ADMIN_ACCOUNT_EDIT, new object[] { accID, username, fullname, accType });
        }

        private void delAction(object sender, EventArgs e)
        {
            int id = this.lv_accounts.SelectedItems[0].Index;
            if (this.lv_accounts.Items[id].Name.Equals("admin") && this.lv_accounts.Items.Find("admin", false).Count() <= 1)
            {
                MessageBox.Show("Phải tồn tại ít nhất một tài khoản quản trị", "Nhắc nhở", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (MessageBox.Show("Bạn có chắc chắn muốn xóa?", "Nhắc nhở", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
            {
                QLNH_BUS_WebServiceSoapClient ws = new QLNH_BUS_WebServiceSoapClient();
                if (ws.RemoveAccount(this.lv_accounts.Items[id].SubItems[0].Text) == true)
                {
                    this._accountList.Remove(this._accountList.Find(a => a.ID.Equals(this.lv_accounts.Items[id].SubItems[0].Text)));
                    MessageBox.Show("Xóa tài khoản thành công");
                    Thread t = new Thread(new ThreadStart(ShowAccount));
                    t.SetApartmentState(ApartmentState.STA);
                    t.Start();
                }
                else
                {
                    MessageBox.Show("Xóa tài khoản thất bại");
                }
            }
        }

        private void bt_newAcc_Click(object sender, EventArgs e)
        {
            this._mainLayout.SwitchForm(FormKey.ADMIN_ACCOUNT_EDIT);
        }

        private void lv_accounts_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                this.ctm_rightClick.Show(this.lv_accounts, e.Location);
            }
        }

        ListViewItemComparer sorter;
        private bool ascending = true;

        private void lv_accounts_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            sorter = new ListViewItemComparer(e.Column);
            sorter.OrderOfSort = (ascending == true) ? SortOrder.Ascending : SortOrder.Descending;
            this.lv_accounts.ListViewItemSorter = sorter;
            this.lv_accounts.Sort();
            ascending = !ascending;
        }

        private string _userNameToFind = "";
        private string _roleToFind = "";

        private void bt_Find_Click(object sender, EventArgs e)
        {
            _userNameToFind = this.searchToolbar.StringToFind;
            _roleToFind = this.searchToolbar.GroupNameToFind;
            //if (this.searchToolbar.GroupToFind != null)
            //    _roleToFind = this.searchToolbar.GroupToFind.ToString();
            //else
            //    _roleToFind = "";

            ShowAccount();
        }

        private void bt_Reload_Click(object sender, EventArgs e)
        {
            _userNameToFind = "";
            _roleToFind = "";

            ShowAccount();
        }

        #endregion
    }
}
